﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Domain.Repositories;
using YAPACS.BusinessObjects.Exams;
using YAPACS.BusinessObjects.Managements.Devices;
using YAPACS.Organizations;
using YAPACS.RisServer.Abstractions;
using YAPACS.RisServer.Services.Dtos;
using YAPACS.Workflows;

namespace YAPACS.RisServer.Controllers;
[Authorize]
public class DeviceController(
    ICurrentUserOrganization currentUserOrganization,
    IRepository<Exam, Guid> examRepository,
    IDeviceService deviceService) : AbpControllerBase
{
    private readonly ICurrentUserOrganization _currentUserOrganization = currentUserOrganization;
    private readonly IRepository<Exam, Guid> _examRepository = examRepository;
    private readonly IDeviceService _deviceService = deviceService;

    /// <summary>
    /// 技师更换设备，获取设备类型
    /// </summary>
    /// <param name="examId"></param>
    /// <returns></returns>
    [HttpGet("api/devices/get-by-exam/{examId}")]
    public async Task<IActionResult> GetDevicesByExam(Guid examId, [FromQuery] string sortProperty, [FromQuery] bool? sortMode)
    {
        IList<DeviceDto> deviceDtos = [];
        var startTime = Clock.Now.Date;
        var endTime = Clock.Now.Date.AddDays(1);
        var exam = await _examRepository.GetAsync(examId);
        var devices = exam.Department.GetDevices().Where(e => e.DeviceType == exam.DeviceType).ToList();
        var exams = (await _examRepository.GetListAsync(e =>
        (e.ExamTime >= startTime && e.ExamTime < endTime)
        || (e.AppointmentTime >= startTime && e.AppointmentTime < endTime)
        || (e.CreationTime >= startTime && e.CreationTime < endTime)))
            .Select(e => new { ExamDeviceOid = e.ExamDevice?.Oid, e.ExamStatus })
            .ToList();
        foreach (var device in devices)
        {
            DeviceDto deviceDto = new();
            var deviceExams = exams.Where(e => e.ExamDeviceOid == device.Oid).ToList();
            deviceDto.CompoundName = device.CompoundName;
            deviceDto.UnCompletedCount = deviceExams.Where(e => e.ExamStatus != ExamStatus.Completed).Count();
            deviceDto.CompletedCount = deviceExams.Where(e => e.ExamStatus == ExamStatus.Completed).Count();
            deviceDto.TotalCount = deviceExams.Count;
            deviceDto.Id = device.Id;
            deviceDtos.Add(deviceDto);
        }
        if (!string.IsNullOrWhiteSpace(sortProperty))
        {
            if (sortProperty == "compoundName")
            {
                if (sortMode.HasValue && sortMode.Value)
                {
                    deviceDtos = deviceDtos.OrderByDescending(d => d.CompoundName).ToList();
                }
                else
                {
                    deviceDtos = deviceDtos.OrderBy(d => d.CompoundName).ToList();
                }
            }
            else if (sortProperty == "unCompletedCount")
            {
                if (sortMode.HasValue && sortMode.Value)
                {
                    deviceDtos = deviceDtos.OrderByDescending(d => d.UnCompletedCount).ToList();
                }
                else
                {
                    deviceDtos = deviceDtos.OrderBy(d => d.UnCompletedCount).ToList();
                }
            }
            else if (sortProperty == "completedCount")
            {
                if (sortMode.HasValue && sortMode.Value)
                {
                    deviceDtos = deviceDtos.OrderByDescending(d => d.CompletedCount).ToList();
                }
                else
                {
                    deviceDtos = deviceDtos.OrderBy(d => d.CompletedCount).ToList();
                }
            }
            else if (sortProperty == "totalCount")
            {
                if (sortMode.HasValue && sortMode.Value)
                {
                    deviceDtos = deviceDtos.OrderByDescending(d => d.TotalCount).ToList();
                }
                else
                {
                    deviceDtos = deviceDtos.OrderBy(d => d.TotalCount).ToList();
                }
            }
        }
        return Ok(new WorkflowOutput
        {
            Success = true,
            Data = new DataGridDto
            {
                RowStyles = new List<string>(),
                Columns = new List<object> {
                    new {
                        DataField="id",
                        Caption= "",
                        Visible=false
                    },
                    new {
                        DataField="compoundName",
                        Caption= "设备"
                    },
                    new {
                        DataField="unCompletedCount",
                        Caption= "未检数"
                    },
                    new {
                        DataField="completedCount",
                        Caption= "已检数"
                    },
                    new {
                        DataField="totalCount",
                        Caption= "总数量"
                    },
                },
                Rows = deviceDtos,
                TotalCount = deviceDtos.Count
            }
        });
    }

    //根据站点或者科室获取设备选项
    [HttpGet("api/devices/get-options")]
    public async Task<IActionResult> GetDeviceOptionsAsync()
    {
        var result = await _deviceService.GetDevicesAsync();
        return Ok(result.ToList().OrderBy(e => e.Order).ThenBy(e => e.CreationTime).Select(e => new
        {
            Label = e.CompoundName,
            Value = e.Oid
        }).ToList());
    }
    [HttpGet("api/devices/getDeviceOption")]
    public async Task<IActionResult> GetDeviceOptions(Guid deviceTypeId)
    {
        var result = await _deviceService.GetDevicesAsync(deviceTypeId);
        return Ok(result.Select(e => new
        {
            Label = e.CompoundName,
            Value = e.Oid
        }).ToList());
    }
}
